<template>
  <div class="zz-multi-lang-input">
    <el-input
      v-model="currentValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :size="size"
      :clearable="clearable"
      @input="handleInput"
      @clear="handleClear"
    >
      <template #append>
        <template v-if="!isSingleLocaleMode">
          <el-popover
            placement="bottom-end"
            width="120"
            trigger="click"
            v-model:visible="popoverVisible"
            :disabled="isSingleLocaleMode"
          >
            <template #reference>
              <el-button
                circle
                size="small"
                :disabled="disabled || isSingleLocaleMode"
                class="lang-btn"
              >
                <el-image
                  :src="currentLocaleIcon"
                  class="language-image"
                  fit="cover"
                  style="width: 25px; height: 18px"
                />
              </el-button>
            </template>
            <el-menu :default-active="currentLocale" @select="handleLocaleChange">
              <el-menu-item
                v-for="locale in availableLocales"
                :key="locale"
                :index="locale"
              >
                <div class="locale-item">
                  <el-image
                    :src="getLocaleIcon(locale)"
                    class="language-image"
                    fit="cover"
                    style="width: 20px; height: 16px; margin-right: 8px"
                  />
                  <span>{{ getLocaleName(locale) }}</span>
                </div>
              </el-menu-item>
            </el-menu>
          </el-popover>
        </template>
        <template v-else>
          <el-button
            circle
            size="small"
            :disabled="true"
            class="lang-btn"
          >
            <el-image
              :src="currentLocaleIcon"
              class="language-image"
              fit="cover"
              style="width: 25px; height: 18px"
            />
          </el-button>
        </template>
      </template>
    </el-input>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import cnFlag from "@/assets/png/cn_flag.png";
import usFlag from "@/assets/png/us_flag.png";

// Props定义
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      availableLocales: ["en_US", "zh_CN"],
      values: {
        en_US: "",
        zh_CN: "",
      },
    }),
    validator: (value) => {
      return (
        value &&
        Array.isArray(value.availableLocales) &&
        typeof value.values === "object"
      );
    },
  },
  singleLocaleMode: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  size: {
    type: String,
    default: "default",
    validator: (value) => ["large", "default", "small", "mini"].includes(value),
  },
  clearable: {
    type: Boolean,
    default: true,
  },
});

// Emits定义
const emit = defineEmits(["update:modelValue", "input", "change", "clear"]);

// 响应式数据
const popoverVisible = ref(false);
const normalizeToUnderscore = (locale) => (locale ? locale.replace(/-/g, "_") : locale);
const normalizeToHyphen = (locale) => (locale ? locale.replace(/_/g, "-") : locale);
const currentLocale = ref(normalizeToUnderscore(localStorage.getItem("language") || "zh-CN"));

const defaultModel = {
  availableLocales: ["en_US", "zh_CN"],
  values: {
    en_US: "",
    zh_CN: "",
  },
};

const internalModel = computed(() => {
  return props.modelValue && typeof props.modelValue === "object"
    ? props.modelValue
    : defaultModel;
});

// 计算属性
const availableLocales = computed(() => {
  const list = internalModel.value.availableLocales || ["en_US", "zh_CN"];
  return list.map((l) => normalizeToUnderscore(l));
});

const currentValue = computed({
  get: () => {
    const values = internalModel.value?.values || {};
    const key = normalizeToUnderscore(currentLocale.value);
    return values[key] ?? values[normalizeToHyphen(key)] ?? "";
  },
  set: (value) => {
    // 这里不直接修改，通过handleInput处理
  },
});

const currentLocaleIcon = computed(() => {
  return getLocaleIcon(currentLocale.value);
});

const isSingleLocaleMode = computed(() => !!props.singleLocaleMode);

// 方法
const getLocaleIcon = (locale) => {
  const l = normalizeToUnderscore(locale);
  switch (l) {
    case "zh_CN":
      return cnFlag;
    case "en_US":
      return usFlag;
    default:
      return cnFlag;
  }
};

const getLocaleName = (locale) => {
  const l = normalizeToUnderscore(locale);
  switch (l) {
    case "zh_CN":
      return "中文";
    case "en_US":
      return "English";
    default:
      return l;
  }
};

const handleInput = (value) => {
  const newValues = { ...internalModel.value.values };
  const key = normalizeToUnderscore(currentLocale.value);
  newValues[key] = value;
  const sanitizedValues = {};
  Object.entries(newValues).forEach(([k, v]) => {
    const kk = normalizeToHyphen(k);
    sanitizedValues[kk] = v;
  });

  const newValue = {
    ...internalModel.value,
    availableLocales: availableLocales.value.map((l) => normalizeToHyphen(l)),
    values: sanitizedValues,
  };

  emit("update:modelValue", newValue);
  emit("input", newValue);
  emit("change", newValue);
};

const handleClear = () => {
  handleInput("");
  emit("clear");
};

const handleLocaleChange = (locale) => {
  if (isSingleLocaleMode.value) return;
  currentLocale.value = locale;
  popoverVisible.value = false;
};

// 监听modelValue变化，更新当前语言
watch(
  () => props.modelValue?.defaultLocale,
  (newLocale) => {
    if (newLocale) {
      currentLocale.value = normalizeToUnderscore(newLocale);
    }
  },
  { immediate: true }
);

// 监听modelValue变化，确保当前语言的值存在
// watch(
//   () => props.modelValue,
//   (newModelValue) => {
//     if (!newModelValue || typeof newModelValue !== "object") return;
//     const values = newModelValue.values || {};
//     const locales = (newModelValue.availableLocales || defaultModel.availableLocales).map((l) => normalizeToHyphen(l));

//     // 确保所有可用语言都有对应的值
//     locales.forEach((locale) => {
//       if (!values.hasOwnProperty(locale)) {
//         console.warn(`Missing value for locale: ${locale}`);
//       }
//     });
//   },
//   { deep: true }
// );

watch(
  () => isSingleLocaleMode.value,
  (v) => {
    if (v) popoverVisible.value = false;
  }
);
</script>

<style scoped>
.zz-multi-lang-input {
  position: relative;
  width: 100%;
}

.lang-btn {
  padding: 0;
  width: 50px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.language-image {
  /* border-radius: 4px; */
  display: block;
}

.lang-btn .language-image {
  margin: 0;
}

/* 确保el-image组件的图片正确显示 */
.language-image .el-image__inner {
  border-radius: inherit;
}

/* 处理加载状态 */
.language-image .el-image__placeholder {
  background-color: #f0f0f0;
  border-radius: inherit;
}

/* 确保下拉菜单中的头像与文字对齐 */
:deep(.el-menu-item) .locale-item {
  display: flex;
  align-items: center;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset;
}

:deep(.el-menu) {
  border: none;
  padding: 0;
}

:deep(.el-menu-item) {
  padding: 8px 16px;
  height: auto;
  line-height: normal;
}

:deep(.el-menu-item.is-active) {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.locale-item {
  display: flex;
  align-items: center;
}
</style>
